package user

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"go-zero-admin/apps/user/api/internal/svc"
	"go-zero-admin/apps/user/api/internal/types"
	"go-zero-admin/apps/user/rpc/user"
	"go-zero-admin/pkg/config"
	"go-zero-admin/pkg/errorx"

	"github.com/golang-jwt/jwt/v4"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq, r *http.Request) (resp *types.LoginResp, err error) {
	fmt.Println("===========> /login", req)
	fmt.Println(errorx.NewDefaultError(errorx.CaptchaErrorCode))
	verifyCode, _ := l.svcCtx.Redis.Get(config.SysLoginCaptchaCachePrefix + req.CaptchaId)
	if verifyCode != req.VerifyCode {
		return nil, errorx.NewDefaultError(errorx.CaptchaErrorCode)
	}
	res, err := l.svcCtx.UserRPC.Login(l.ctx, &user.LoginReq{
		Account:    req.Account,
		Password:   req.Password,
		CaptchaId:  req.CaptchaId,
		HeaderGet:  r.Header.Get("X-Forwarded-For"),
		RequestURI: r.RequestURI,
	})
	fmt.Println("============》 err", err)
	if err != nil {
		fmt.Println("============》 err", err)

		return nil, err
	}
	//_, err = l.svcCtx.Redis.Del(req.CaptchaId)

	return &types.LoginResp{Token: res.Token}, nil
}

func (l *LoginLogic) getJwtToken(userId int64) (string, error) {
	iat := time.Now().Unix()
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + l.svcCtx.Config.JwtAuth.AccessExpire
	claims["iat"] = iat
	claims[config.SysJwtUserId] = userId
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(l.svcCtx.Config.JwtAuth.AccessSecret))

}
